/**
 * 串行任务执行
 * new SerialTask(3, (result||error)=> {
 *   // 结束
 * }).start((index, result)=> {
 *  
 * })
 * @author xiufu.wang
 */

export default class SerialTask{
    constructor(len, overFn) { 
        this.len = len
        this.index = 0
        this.overFn = overFn
        this.result = null
        this.err = null
    }
    start(taskFn) { 
        if (this.index > this.len-1 || this.err) {
            this.overFn(this.err || this.result)
        } else {
            const res = taskFn(this.index, this.result)
            Promise.resolve(res).then((v) => {
                this.index++
                this.result = v
                this.start(taskFn)
            }).catch((err) => {
                this.index++
                this.err = err
                this.start(taskFn)
            })
        }
    }
}